package com.sky.aspect;


import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    @Pointcut(" execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill) ")
    public void autoFillPointCut(){}

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchFieldException, IllegalAccessException {
      log.info("开始自动填充公共属性");
        //判断是insert方法还是update方法
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = annotation.value();
        //获得方法的参数
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0){
            return;
        }
        Object entity = args[0];
        Class clazz = entity.getClass();
        Field updateTime = clazz.getDeclaredField("updateTime");
        Field updateUser = clazz.getDeclaredField("updateUser");
        if(value == OperationType.INSERT){
            Field createTime = clazz.getDeclaredField("createTime");
            Field createUser = clazz.getDeclaredField("createUser");
            updateUser.setAccessible(true);
            updateUser.set(entity, BaseContext.getCurrentId());
            createUser.setAccessible(true);
            createUser.set(entity,BaseContext.getCurrentId());
            updateTime.setAccessible(true);
            updateTime.set(entity,LocalDateTime.now());
            createTime.setAccessible(true);
            createTime.set(entity,LocalDateTime.now());

        }else {
            updateTime.setAccessible(true);
            updateTime.set(entity,LocalDateTime.now());
            updateUser.setAccessible(true);
            updateUser.set(entity, BaseContext.getCurrentId());
        }
    }
}
